<template>
	<view>
		<u-navbar :border-bottom="true" title="扫码登录"></u-navbar>
		<view class="banner">
			<view class="bg-icon text-grey iconfont icon-PC">
				<view v-if="state==40000" class="state-icon text-grey iconfont icon-tanhao">
				
				</view>
				<view v-if="state==20000" class="state-icon text-grey iconfont icon-erweima">
				
				</view>
			</view>
		</view>
		<view v-if="state==40000">
			<view class="text-center u-font-32">二维码已失效</view>
		</view>
		<view v-if="state==20000">
			<view class="text-center u-font-32">正在尝试PC端扫码登录</view>
			<view class="text-center u-font-32">请确认是否为本人操作</view>
		</view>
		<view class="u-p-30"></view>
		<view class="btn bg-theme" @tap="scan()" v-if="state==40000">
			重新扫描
		</view>
		<view class="btn bg-theme" @tap="confirm()" v-if="state==20000">
			确认登录
		</view>
		<view class="btn" @tap="cancel()" v-if="state==20000">
			取消登录
		</view>
	</view>
</template>

<script>
	import {checkQrcode,handleQrcode} from "@/api/user.js"
	import { goback, toast ,delay} from "@/utils/util";
	export default {
		data() {
			return {
				id:'',
				state:0,
				loading:false
			};
		},
		onLoad({id}) {
			this.id = id
			this.fetchState()
		},
		methods:{
			async scan(){
				const {result} = await new Promise((resolve,reject)=>{
					uni.scanCode({
						scanType:['qrCode'],
						success:resolve,
						fail:reject
					})
				})
				if(/^login:qr:/.test(result)){
					this.id = result.slice(9)
					this.fetchState()
				}
			},
			async fetchState(){
				const {statusCode} = await checkQrcode(this.id)
				this.state = statusCode
			},
			async confirm(){
				if(this.loading){
					throw new Error('正在请求中...')
				}
				try{
					this.loading = true
					uni.showLoading({
						title:'登录中...'
					})
					const {statusCode} = await handleQrcode(this.id,'confirm')
					this.state = statusCode
					if(statusCode===30000){
						uni.hideLoading()
						toast('登录成功')
						await delay(1000)
						goback()
					}
				}finally{
					this.loading = false
					uni.hideLoading()
				}
			},
			async cancel(){
				if(this.loading){
					throw new Error('正在请求中...')
				}
				try{
					this.loading = true
					const {statusCode} = await handleQrcode(this.id,'cancel')
					this.state = statusCode
					toast('已取消登录')
					await delay(1000)
				}finally{
					goback()
					this.loading = false
				}
			}
		}
	}
</script>
<style>
	page{
		background-color: #ffffff;
	}
</style>
<style lang="scss" scoped>
	.banner{
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 70rpx 0 10rpx;
		.bg-icon{
			font-size: 300rpx;
			position: relative;
		}
		.state-icon{
			position: absolute;
			left: 50%;
			top: 42%;
			transform: translate(-50%,-50%);
			font-size: 70rpx;
		}
	}
	.btn{
		margin: 0 50rpx;
		padding: 20rpx 0;
		text-align: center;
		font-size: 32rpx; 
		border-radius: 10rpx;
		&+.btn{
			margin-top: 20rpx;
		}
	}
</style>
